package auth_model

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"time"
)

// Admin 管理员用户
type Admin struct {
	ID        int64     `gorm:"primaryKey;autoIncrement" json:"id"`
	Username  string    `gorm:"type:varchar(64);uniqueIndex;not null" json:"username"`
	Password  string    `gorm:"type:varchar(255);not null" json:"-"`
	Nickname  string    `gorm:"type:varchar(64)" json:"nickname"`
	Avatar    string    `gorm:"type:varchar(255)" json:"avatar"`
	Email     string    `gorm:"type:varchar(255)" json:"email"`
	Mobile    string    `gorm:"type:varchar(20)" json:"mobile"`
	RoleID    int64     `gorm:"type:bigint;not null;index" json:"role_id"`
	Status    int8      `gorm:"type:tinyint(1);default:1" json:"status"` // 0=禁用 1=启用
	CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}

// TableName 指定用户表名
func (Admin) TableName() string {
	return "admins"
}

// BeforeSave 在保存用户前加密密码
func (a *Admin) BeforeSave(tx *gorm.DB) error {
	if a.Password != "" {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(a.Password), bcrypt.DefaultCost)
		if err != nil {
			return err
		}
		a.Password = string(hashedPassword)
	}
	return nil
}

// 校验密码
func (a *Admin) CheckPassword(password, hashedPassword string) bool {
	return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) == nil
}
